const { resolve } = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// css文件压缩处理
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin')
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');

module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/[name].[contenthash:5].js',
    path: resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      // loader的配置
      {
        // 处理css资源
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            // 还需要在package.json中定义browserslist
            loader: 'postcss-loader',
            options: {
              'postcssOptions':{
                plugins:['postcss-preset-env']
              }
            }
          }
        ]
      },
      {
        // 处理html中img资源
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.js$/,
        include:[
            resolve(__dirname,'./src')
        ],
        use:[
            {
                loader: 'babel-loader',
                options: {
                // 预设：指示babel做怎么样的兼容性处理
                presets: [
                    [
                    '@babel/preset-env',
                    {
                        // 按需加载
                        useBuiltIns: 'usage',
                        // 指定core-js版本
                        corejs: {
                        version: 3
                        },
                        // 指定兼容性做到哪个版本浏览器
                        targets: {
                        chrome: '60',
                        firefox: '60',
                        ie: '9',
                        safari: '10',
                        edge: '17'
                        }
                    }
                    ]
                ]
                }
            }
        ]
      }
    ]
  },
  plugins: [
    // plugins的配置
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
      filename:'css/[name].[contenthash:5].css'
    }),
    // css压缩
    new CssMinimizerWebpackPlugin(),
    // 告诉webpack哪些库不参与打包，同时使用时的名称也变为``共享依赖库映射的名称~
    new webpack.DllReferencePlugin({
      manifest: resolve(__dirname, './dll/manifest.json')
    }),
    // 将某个文件打包输出去，并在html中自动引入该资源
    new AddAssetHtmlWebpackPlugin({
      //如没有配置‘publicPath’，那么在html中script标签多了一个目录auto
      publicPath: './',
      filepath: resolve(__dirname, './dll/vendor.js')
    })
  ],
  mode: 'development',
  devServer: {
    compress: true,
    port: 3001,
    open: true,
    // 开启HMR功能
    // 当修改了webpack配置，新配置要想生效，必须重新webpack服务
    hot: true
  },
  devtool: 'source-map'
};